package com.xxwy.springboot.webflux.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author xxwy
 * on 2018/8/16 0016
 */
@RestController
@Slf4j
public class Testcontroller {

    @GetMapping("/0")
    public String get() throws InterruptedException {
        log.info("get start");
        TimeUnit.SECONDS.sleep(5);
        log.info("over ");
        return "some string";
    }

    @Async
    @GetMapping("/1")
    public String get1() throws InterruptedException {
        log.info("get start");
        TimeUnit.SECONDS.sleep(5);
        log.info("over ");
        return "some string";
    }

    @GetMapping("2")
    public Mono<String> get2() throws InterruptedException {
        log.info("get start");
        Mono<String> result = Mono.fromSupplier(()->{
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "some thing";
        });
        log.info("over");
        return result;
    }

    @GetMapping(value = "3",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> get3() throws InterruptedException {
        log.info("get start");
        Flux<String> result = Flux.fromStream(IntStream.range(1, 5).mapToObj(i -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "flux data -- " + i;
        }));
        log.info("over");
        return result;
    }
}
